from typing import Any, List, Optional, Dict

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.db.session import get_db
from app.models.pua import PUAPattern
from app.services.analysis.pua_detector import pua_detector
from app.models.message import Message
from app.schemas.message import MessageQuery
import app.crud.message as crud_message

router = APIRouter()


@router.get("/patterns")
async def get_pua_patterns(
    db: AsyncSession = Depends(get_db),
    category: Optional[str] = None,
) -> Any:
    """
    获取PUA模式列表
    
    - **category**: 按类别筛选
    """
    # 构建查询
    query = db.query(PUAPattern)
    
    if category:
        query = query.filter(PUAPattern.category == category)
    
    # 执行查询
    patterns = await query.all()
    
    # 格式化结果
    result = []
    for pattern in patterns:
        import json
        examples = []
        try:
            if pattern.examples:
                examples = json.loads(pattern.examples)
        except:
            pass
        
        response_templates = []
        try:
            if pattern.response_templates:
                response_templates = json.loads(pattern.response_templates)
        except:
            pass
        
        result.append({
            "id": pattern.id,
            "pattern": pattern.pattern,
            "category": pattern.category,
            "description": pattern.description,
            "severity": pattern.severity,
            "examples": examples,
            "response_templates": response_templates
        })
    
    return result


@router.get("/categories")
async def get_pua_categories() -> Any:
    """
    获取PUA模式类别列表
    """
    from app.models.pua import PUAPatternCategory
    
    categories = [
        {
            "id": "gaslighting",
            "name": "煤气灯效应",
            "description": "让对方怀疑自己的感受和记忆"
        },
        {
            "id": "love_bombing",
            "name": "爱情轰炸",
            "description": "短时间内提供过度的关注和喜爱"
        },
        {
            "id": "negging",
            "name": "负面评价",
            "description": "通过批评降低对方的自尊心"
        },
        {
            "id": "isolation",
            "name": "隔离控制",
            "description": "试图切断对方与他人的联系"
        },
        {
            "id": "triangulation",
            "name": "三角关系",
            "description": "引入第三者制造不安全感"
        },
        {
            "id": "silent_treatment",
            "name": "冷暴力",
            "description": "通过沉默来惩罚对方"
        },
        {
            "id": "guilt_tripping",
            "name": "罪恶感操纵",
            "description": "制造罪恶感来控制对方行为"
        },
        {
            "id": "breadcrumbing",
            "name": "面包屑喂养",
            "description": "仅给予最低限度的关注来维持关系"
        },
        {
            "id": "other",
            "name": "其他",
            "description": "其他类型的PUA手段"
        }
    ]
    
    return categories


@router.get("/resources")
async def get_educational_resources() -> Any:
    """
    获取PUA防护教育资源
    """
    resources = [
        {
            "title": "识别情感操控",
            "description": "学习如何识别常见的情感操控手段",
            "url": "https://example.com/emotional-manipulation",
            "type": "article"
        },
        {
            "title": "设立健康边界",
            "description": "关于如何在人际关系中设立健康边界的指南",
            "url": "https://example.com/healthy-boundaries",
            "type": "guide"
        },
        {
            "title": "PUA话术解析",
            "description": "常见PUA话术的详细解析和应对方法",
            "url": "https://example.com/pua-analysis",
            "type": "video"
        },
        {
            "title": "心理咨询资源",
            "description": "提供专业心理咨询的机构和资源",
            "url": "https://example.com/counseling-resources",
            "type": "resources"
        }
    ]
    
    return resources


@router.post("/analyze-and-respond")
async def analyze_and_respond(
    text: str,
    age_group: Optional[str] = Query(None, description="User age group (adult, teen, elderly)"),
    relationship_context: Optional[str] = Query(None, description="Relationship context (dating, friendship, professional, family)"),
    priority: Optional[str] = Query("balanced", description="Analysis priority: safety, education, or balanced"),
    context_messages: Optional[List[Dict[str, str]]] = None
) -> Any:
    """
    深度分析PUA内容并提供个性化应对策略
    
    对文本进行PUA分析，并根据用户情况提供量身定制的应对策略和教育资源
    
    - **text**: 待分析的文本内容
    - **age_group**: 用户年龄组 (adult, teen, elderly)
    - **relationship_context**: 关系背景 (dating, friendship, professional, family)
    - **priority**: 分析优先级 (safety, education, balanced)
    - **context_messages**: 上下文消息列表，格式为[{"role": "user|sender", "content": "消息内容"}]
    """
    # 使用增强的上下文感知PUA检测
    detection_result = await pua_detector.detect_pua_with_context(
        text=text,
        context_messages=context_messages,
        relationship_context=relationship_context,
        severity_threshold=0.2  # 略微降低阈值以提高检测灵敏度
    )
    
    # 获取教育资源
    resources = await get_educational_resources()
    
    # 获取PUA类别信息
    categories = await get_pua_categories()
    categories_dict = {cat["id"]: cat for cat in categories}
    
    # 提取检测到的类别
    detected_categories = []
    if "detected_patterns" in detection_result and detection_result["detected_patterns"]:
        detected_categories = [pattern["category"] for pattern in detection_result["detected_patterns"]]
        # 去重
        detected_categories = list(set(detected_categories))
    
    # 根据检测到的类别，筛选更相关的资源
    relevant_resources = []
    if detected_categories:
        # 这里可以根据检测到的类别匹配最相关的资源
        for resource in resources:
            # 简单实现：将所有资源添加为相关资源
            relevant_resources.append(resource)
    else:
        # 如果没有检测到PUA，则提供一般性的教育资源
        relevant_resources = resources[:2]  # 限制为前2个
    
    # 根据用户情况生成个性化应对策略
    personalized_strategies = []
    safety_tips = []
    
    # 根据年龄组提供不同的策略
    age_specific_advice = ""
    if age_group == "teen":
        age_specific_advice = "作为年轻人，建议你与信任的成年人(如父母、老师或辅导员)分享这些信息，获取支持和建议。"
        safety_tips.append("当感到不舒服时，可以礼貌地结束对话或寻求朋友帮助")
        safety_tips.append("保护个人信息，不要轻易分享私人照片或详细联系方式")
    elif age_group == "elderly":
        age_specific_advice = "注意保护个人信息和财产安全，遇到疑似PUA言论时可以咨询家人或社工。"
        safety_tips.append("对任何试图隔离你或索取财物的行为保持警惕")
        safety_tips.append("与家人保持定期联系，分享你的社交活动和新认识的人")
    else:  # adult
        age_specific_advice = "了解这些模式可以帮助你在人际关系中维护健康界限。"
        safety_tips.append("信任你的直觉，如果某段对话让你感到不适，这可能是一个重要的警示信号")
        safety_tips.append("设立并坚守你的个人界限，不要因为压力而妥协")
    
    # 根据关系背景提供建议
    context_specific_advice = ""
    if relationship_context == "dating":
        context_specific_advice = "在约会关系中，健康的互动应该建立在平等、尊重和良好沟通的基础上。"
        personalized_strategies.append("可以明确表达：'我需要我们的关系建立在相互尊重的基础上'")
        personalized_strategies.append("当感到不舒服时，可以说：'我需要一些时间思考这个问题'")
    elif relationship_context == "friendship":
        context_specific_advice = "友谊应当是支持和积极的，任何试图控制或贬低你的行为都值得重新评估这段关系。"
        personalized_strategies.append("可以尝试说：'作为朋友，我希望我们的交流能更加积极和支持'")
        personalized_strategies.append("设立界限：'我重视我们的友谊，但也需要我自己的空间和时间'")
    elif relationship_context == "professional":
        context_specific_advice = "职场中的PUA行为可能构成骚扰，了解你的权利和公司的相关政策很重要。"
        personalized_strategies.append("建议保留相关证据，必要时向HR部门或管理层反映")
        personalized_strategies.append("保持专业：'让我们专注于工作内容和项目目标'")
    elif relationship_context == "family":
        context_specific_advice = "家庭关系中的操控模式可能根深蒂固，专业咨询可能会有所帮助。"
        personalized_strategies.append("设立健康界限：'我理解你的想法，但我需要按自己的方式做决定'")
        personalized_strategies.append("寻求支持：'我们可以一起寻求专业帮助改善我们的沟通方式'")
    
    # 构建最终响应
    response = {
        "detection_result": detection_result,
        "deep_analysis": {
            "detected_categories": detected_categories,
            "personalized_advice": {
                "age_specific": age_specific_advice,
                "context_specific": context_specific_advice,
                "general_strategies": personalized_strategies,
                "safety_tips": safety_tips
            },
            "educational_resources": relevant_resources[:3],  # 限制为前3个最相关的资源
            "priority_focus": priority
        }
    }
    
    # 如果LLM已经提供了这些字段，则不需要重复添加
    if "long_term_advice" not in detection_result and relationship_context:
        # 为不同关系背景生成长期建议
        if relationship_context == "dating":
            response["deep_analysis"]["long_term_advice"] = "在恋爱关系中，注意观察模式而非单一事件。如果操控行为形成模式，应考虑关系的健康度。"
        elif relationship_context == "friendship":
            response["deep_analysis"]["long_term_advice"] = "友谊应该增强而非削弱你的自信和快乐。持续评估这段关系是否真正支持你的成长。"
        elif relationship_context == "professional":
            response["deep_analysis"]["long_term_advice"] = "在职场环境中，建立专业网络和支持系统，记录不当行为，了解公司政策和申诉渠道。"
        elif relationship_context == "family":
            response["deep_analysis"]["long_term_advice"] = "家庭动态可能很复杂，考虑家庭治疗或心理咨询，学习设立健康界限的方法。"
    
    return response


@router.post("/analyze-conversation")
async def analyze_conversation(
    contact_id: Optional[int] = None,
    session_id: Optional[int] = None,
    timeframe: Optional[str] = Query("all", description="Timeframe for analysis (all, recent, last_week, last_month)"),
    message_limit: int = Query(200, description="Maximum number of messages to analyze"),
    relationship_context: Optional[str] = Query(None, description="Relationship context (dating, friendship, professional, family)"),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """
    分析对话历史中的PUA模式和发展趋势
    
    深入分析对话历史，识别PUA模式的发展和升级趋势，提供长期防护策略
    
    - **contact_id**: 联系人ID (与session_id二选一)
    - **session_id**: 会话ID (与contact_id二选一)
    - **timeframe**: 分析时间范围 (all, recent, last_week, last_month)
    - **message_limit**: 最大分析消息数量
    - **relationship_context**: 关系背景 (dating, friendship, professional, family)
    """
    # 验证参数
    if not contact_id and not session_id:
        raise HTTPException(
            status_code=400,
            detail="必须提供contact_id或session_id"
        )
    
    # 构建查询
    time_filter = {}
    import datetime
    now = datetime.datetime.now()
    
    if timeframe == "recent":
        # 最近50条消息，不添加时间筛选
        message_limit = min(message_limit, 50)
    elif timeframe == "last_week":
        last_week = now - datetime.timedelta(days=7)
        time_filter["start_time"] = last_week
    elif timeframe == "last_month":
        last_month = now - datetime.timedelta(days=30)
        time_filter["start_time"] = last_month
    
    # 获取消息记录
    query = MessageQuery(
        contact_id=contact_id,
        session_id=session_id,
        limit=message_limit,
        **time_filter
    )
    
    messages = await crud_message.get_messages_by_query(db, query=query)
    
    if not messages:
        raise HTTPException(
            status_code=404,
            detail="根据条件未找到消息记录"
        )
    
    # 将ORM对象转换为字典
    messages_dict = [
        {
            "id": msg.id,
            "contact_id": msg.contact_id,
            "session_id": msg.session_id,
            "direction": msg.direction,
            "msg_type": msg.msg_type,
            "content": msg.content,
            "sent_at": msg.sent_at,
            "status": msg.status
        }
        for msg in messages
    ]
    
    # 分组消息，便于按照时间顺序分析
    from itertools import groupby
    from datetime import datetime, timedelta
    
    # 按照发送日期分组(按天)
    def get_date_key(msg):
        sent_at = msg["sent_at"]
        if isinstance(sent_at, str):
            sent_at = datetime.fromisoformat(sent_at.replace('Z', '+00:00'))
        return sent_at.date()
    
    # 排序消息
    sorted_messages = sorted(messages_dict, key=lambda x: x["sent_at"])
    
    # 按日期分组
    grouped_messages = []
    for date, day_messages in groupby(sorted_messages, key=get_date_key):
        day_messages_list = list(day_messages)
        grouped_messages.append({
            "date": date.isoformat(),
            "messages": day_messages_list,
            "count": len(day_messages_list)
        })
    
    # 对每组消息进行PUA分析
    for group in grouped_messages:
        # 只分析文本消息
        text_messages = [msg for msg in group["messages"] if msg["msg_type"] == "text" and msg["content"]]
        
        # 初始化组统计信息
        group["pua_statistics"] = {
            "total_messages": len(text_messages),
            "pua_messages": 0,
            "categories": {},
            "severity_sum": 0
        }
        
        # 分析每条消息
        detected_messages = []
        for msg in text_messages:
            # 只检测来自对方的消息(direction="incoming")
            if msg["direction"] == "incoming" and msg["content"]:
                try:
                    detection_result = await pua_detector.detect_pua(msg["content"])
                    
                    # 如果检测到PUA
                    if detection_result.is_pua:
                        group["pua_statistics"]["pua_messages"] += 1
                        group["pua_statistics"]["severity_sum"] += detection_result.score
                        
                        # 统计类别
                        for pattern in detection_result.detected_patterns:
                            category = pattern["category"]
                            if category in group["pua_statistics"]["categories"]:
                                group["pua_statistics"]["categories"][category] += 1
                            else:
                                group["pua_statistics"]["categories"][category] = 1
                        
                        # 保存结果
                        detected_messages.append({
                            "message_id": msg["id"],
                            "content": msg["content"],
                            "detection_result": {
                                "is_pua": detection_result.is_pua,
                                "score": detection_result.score,
                                "risk_level": detection_result.risk_level,
                                "detected_patterns": detection_result.detected_patterns
                            }
                        })
                
                except Exception as e:
                    continue
        
        # 计算平均PUA评分
        if group["pua_statistics"]["pua_messages"] > 0:
            group["pua_statistics"]["avg_severity"] = group["pua_statistics"]["severity_sum"] / group["pua_statistics"]["pua_messages"]
        else:
            group["pua_statistics"]["avg_severity"] = 0
            
        # 保存检测到的消息
        group["detected_pua_messages"] = detected_messages
        
        # 删除不需要的字段，减小响应大小
        del group["messages"]
    
    # 分析整体趋势
    trend_analysis = {
        "total_days": len(grouped_messages),
        "total_messages": sum(group["pua_statistics"]["total_messages"] for group in grouped_messages),
        "total_pua_messages": sum(group["pua_statistics"]["pua_messages"] for group in grouped_messages),
        "overall_categories": {},
        "progression": "stable"  # 默认为稳定
    }
    
    # 计算总体类别统计
    for group in grouped_messages:
        for category, count in group["pua_statistics"]["categories"].items():
            if category in trend_analysis["overall_categories"]:
                trend_analysis["overall_categories"][category] += count
            else:
                trend_analysis["overall_categories"][category] = count
    
    # 按数量排序类别
    trend_analysis["top_categories"] = [
        {"category": k, "count": v}
        for k, v in sorted(
            trend_analysis["overall_categories"].items(),
            key=lambda item: item[1],
            reverse=True
        )
    ][:5]  # 获取前5个
    
    # 分析趋势
    if len(grouped_messages) >= 3:
        # 计算PUA消息比例趋势
        ratios = []
        for group in grouped_messages:
            stats = group["pua_statistics"]
            if stats["total_messages"] > 0:
                ratios.append(stats["pua_messages"] / stats["total_messages"])
            else:
                ratios.append(0)
        
        # 简单线性趋势分析
        if len(ratios) >= 3:
            first_third = sum(ratios[:len(ratios)//3]) / (len(ratios)//3) if len(ratios)//3 > 0 else 0
            last_third = sum(ratios[-len(ratios)//3:]) / (len(ratios)//3) if len(ratios)//3 > 0 else 0
            
            if last_third > first_third * 1.25:
                trend_analysis["progression"] = "escalating"
            elif last_third < first_third * 0.75:
                trend_analysis["progression"] = "decreasing"
    
    # 根据关系背景生成建议
    relation_advice = ""
    if relationship_context:
        if relationship_context == "dating":
            relation_advice = "在约会关系中，PUA话术往往从微妙的赞美和关注开始，逐渐转向控制和贬低。关注这种模式的变化是很重要的。"
        elif relationship_context == "friendship":
            relation_advice = "朋友关系中的操控可能以开玩笑的形式出现，但随着时间的推移可能会更加明显和有害。"
        elif relationship_context == "professional":
            relation_advice = "职场环境中的PUA可能与权力动态相关，注意是否有人利用职位优势进行情感操控。"
        elif relationship_context == "family":
            relation_advice = "家庭关系中的PUA模式往往根深蒂固且复杂，可能与代际传递的互动模式有关。"
    
    # 构建最终响应
    response = {
        "timeframe": timeframe,
        "relationship_context": relationship_context,
        "message_statistics": {
            "total_analyzed": trend_analysis["total_messages"],
            "total_pua_detected": trend_analysis["total_pua_messages"],
            "pua_ratio": trend_analysis["total_pua_messages"] / trend_analysis["total_messages"] if trend_analysis["total_messages"] > 0 else 0
        },
        "daily_analysis": grouped_messages,
        "trend_analysis": trend_analysis,
        "recommendations": {
            "relationship_specific_advice": relation_advice,
            "suggested_actions": []
        }
    }
    
    # 根据趋势生成建议
    if trend_analysis["progression"] == "escalating":
        response["recommendations"]["suggested_actions"] = [
            "PUA模式呈现上升趋势，建议提高警惕，并考虑设立更明确的界限",
            "记录不舒适的互动，以便识别模式",
            "考虑咨询专业人士以获取针对性支持"
        ]
    elif trend_analysis["progression"] == "stable" and trend_analysis["total_pua_messages"] > 0:
        response["recommendations"]["suggested_actions"] = [
            "虽然PUA模式保持稳定，但仍需关注这些模式对你的影响",
            "尝试不同的回应策略，观察对方反应",
            "学习更多关于健康关系的知识"
        ]
    elif trend_analysis["progression"] == "decreasing":
        response["recommendations"]["suggested_actions"] = [
            "PUA模式呈现下降趋势，这可能是积极的迹象",
            "继续保持设立的界限",
            "密切关注未来互动中的任何变化"
        ]
    else:
        response["recommendations"]["suggested_actions"] = [
            "保持警惕，学习识别PUA话术的方法",
            "设立并坚守个人界限",
            "优先考虑自己的情感健康和直觉"
        ]
    
    return response